<?php

namespace app\admin\controller\xykeep;

use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 门店管理
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{

    /**
     * Store模型对象
     * @var \app\admin\model\xykeep\Store
     */
    protected $model = null;
    protected $categoryModel = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\Store;
        $this->view->assign("isDefaultList", $this->model->getIsDefaultList());
        $this->view->assign("statusList", $this->model->getStatusList());

    }

    /**
	 * 选择
	 */
	public function select()
	{
	    if ($this->request->isAjax()) {
	        return $this->index();
	    }
	    return $this->view->fetch();
	}

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            //陈俊东 自动添加管理员
            //自动创建管理员信息
            $admin_insert['password'] = $params['password'];
            $admin_insert['username'] = $admin_insert['mobile'] = $params['phone'];
            $admin_insert['nickname'] = $params['name'];
            $admin_insert['salt'] = Random::alnum();
            $admin_insert['password'] = $this->auth->getEncryptPassword($admin_insert['password'], $admin_insert['salt']);
            $admin_insert['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。

            $store_id = $this->model->allowField(true)->insertGetId($params);

            $admin_insert['store_id'] = $store_id;
            $admin_id = Db::name('admin')->insertGetId($admin_insert);
            Db::name('auth_group_access')->insert(['uid' => $admin_id, 'group_id' => '6']);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        //陈俊东 事务操作
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $store_update = $params;
            if($params['password']==''){
                unset($store_update['password']);
            }
            $result = $row->allowField(true)->save($store_update);

            //陈俊东 密码更新
            $admin_update['nickname'] = $params['name'];
            $admin_update['username'] = $params['phone'];
            if($params['password']){
                if(strlen($params['password']) >= 6){
                    $admin_update['password'] = $params['password'];
                    $admin_update['salt'] = Random::alnum();
                    $admin_update['password'] = $this->auth->getEncryptPassword($admin_update['password'], $admin_update['salt']);
                }else{
                    throw new Exception('密码长度不能小于6');
                }

            }
            $result = Db::name('admin')
                ->where('store_id', $ids)  // 根据管理员 ID 查找对应记录
                ->update($admin_update);  // 更新记录

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                Db::name('admin')->where('store_id',$item->id)->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
